package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"post-pro/cache"
	"post-pro/models"
	"time"
)

func GetArticleList(c *gin.Context) {
	var articles []models.Article
	redis_list_key := "article_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Debug().Find(&articles)
		jsonData, _ := json.Marshal(articles)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &articles)
	}

	c.JSON(200, gin.H{
		"message": "列表展示成功",
		"code":    200,
		"list":    articles,
	})
	return
}

func GetArticleDetail(c *gin.Context) {
	var article models.Article
	id := c.Query("id")

	redis_detail_key := "article_detail"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).Debug().First(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &article)
	}

	c.JSON(200, gin.H{
		"message": "详情展示成功",
		"code":    200,
		"data":    article,
	})
	return
}
